use ratatui::{
    backend::Backend,
    layout::{Constraint, Direction, Layout},
    widgets::{Block, Borders},
    Terminal,
};
use tui_textarea::{Input, Key, TextArea};
use crossterm::event::{self, Event, KeyCode, KeyEvent, KeyModifiers};
use std::time::Duration;

pub struct CommentForm {
    pub comment: TextArea<'static>,
}

impl CommentForm {
    pub fn new() -> Self {
        let mut comment = TextArea::default();
        comment.set_block(Block::default().title("请输入评论内容").borders(Borders::ALL));
        CommentForm { comment }
    }

    pub fn handle_event(&mut self, event: Event) -> bool {
        if let Event::Key(key_event) = event {
            if key_event.code == KeyCode::Esc {
                return true; // 提交
            }

            if let Some(input) = convert_key_event(key_event) {
                self.comment.input(input);
            }
        }
        false
    }

    pub fn render<B: Backend>(&mut self, terminal: &mut Terminal<B>) -> Result<(), std::io::Error> {
        terminal.draw(|f| {
            let chunks = Layout::default()
                .direction(Direction::Vertical)
                .margin(4)
                .constraints([Constraint::Min(3)])
                .split(f.size());

            f.render_widget(&self.comment, chunks[0]);
        })?;
        Ok(())
    }

    pub fn get_comment(&self) -> String {
        self.comment.lines().join("\n")
    }
}

fn convert_key_event(ev: KeyEvent) -> Option<Input> {
    let key = match ev.code {
        KeyCode::Char(c) => Key::Char(c),
        KeyCode::Enter => Key::Enter,
        KeyCode::Tab => Key::Tab,
        KeyCode::Backspace => Key::Backspace,
        KeyCode::Delete => Key::Delete,
        KeyCode::Left => Key::Left,
        KeyCode::Right => Key::Right,
        KeyCode::Up => Key::Up,
        KeyCode::Down => Key::Down,
        KeyCode::Home => Key::Home,
        KeyCode::End => Key::End,
        KeyCode::PageUp => Key::PageUp,
        KeyCode::PageDown => Key::PageDown,
        _ => return None,
    };

    Some(Input {
        key,
        ctrl: ev.modifiers.contains(KeyModifiers::CONTROL),
        alt: ev.modifiers.contains(KeyModifiers::ALT),
        shift: ev.modifiers.contains(KeyModifiers::SHIFT),
    })
}
